package class02;

/**
 * @description: 根据系统提供的不等随机机制，加工出等概率随机机制
 * @time: 2021/7/17 14:20
 * @author: lhy
 */
public class EqualProbabilityRandom {
    public static class RandomBox {
        private final double p;
        // 初始化时请一定满足：0 < zeroP < 1
        public RandomBox(double p) {
            this.p = p;
        }
        public int random() {
            return Math.random() < p ? 0 : 1;
        }

    }
    /**根据RandomBox随即机制 如何加工出等概率返回0和1的函数
     * 假设 RandomBox 以概率 p 返回 0 ，以概率 (1-p) 返回1
     * 0 0 p^2
     * 0 1 p(1-p)
     * 1 0 p(1-p)
     * 1 1 (1-p)^2
     * @return 等概率返回 0 和 1
     */
    public static int equalProbability0And1(RandomBox rb){
        int first;
        do {
            first = rb.random();
        }while (first == rb.random());
        return first;
    }

    public static void main(String[] args) {
        int testTimes = 100000;
        double p = 0.78;
        RandomBox randomBox = new RandomBox(p);
        int[] count = new int[2];
        for (int i = 0; i < testTimes; i++) {
            count[equalProbability0And1(randomBox)]++;
        }
        System.out.println("Count(0) = " + count[0]);
        System.out.println("Count(1) = " + count[1]);
    }
}
